package com.androidmvp.dreammvp.simple7.base;

import com.androidmvp.dreammvp.simple7.base.MvpCallback;
import com.androidmvp.dreammvp.simple7.base.MvpPresenter;
import com.androidmvp.dreammvp.simple7.base.MvpView;

/**
 * 作者: Dream on 2017/9/4 22:31
 * QQ:510278658
 * E-mail:510278658@qq.com
 */

//直接封装MVP实现
public class ProxyMvpCallback<V extends MvpView, P extends MvpPresenter<V>> implements MvpCallback<V, P> {

    //持有目标对象引用->Activity
    //mvpCallback->本质就是Actiivty
    private MvpCallback<V, P> mvpCallback;

    public ProxyMvpCallback(MvpCallback<V, P> mvpCallback){
        this.mvpCallback = mvpCallback;
    }

    @Override
    public P createPresenter() {
        P presenter = mvpCallback.getPresenter();
        if (presenter == null) {
            presenter = mvpCallback.createPresenter();
        }
        if (presenter == null) {
            throw new NullPointerException("Presenter is not null!");
        }

        // 绑定
        mvpCallback.setPresenter(presenter);
        return getPresenter();
    }

    @Override
    public V createView() {
        V view = mvpCallback.getView();
        if (view == null) {
            view = mvpCallback.createView();
        }
        if (view == null) {
            throw new NullPointerException("Presenter is not null!");
        }

        // 绑定
        mvpCallback.setView(view);
        return getView();
    }

    @Override
    public void setView(V view) {
        this.mvpCallback.setView(view);
    }

    /**
     * 获取presenter
     *
     * @return
     */
    @Override
    public P getPresenter() {
        P presenter = mvpCallback.getPresenter();
        if (presenter == null) {
            // 抛异常
            throw new NullPointerException("Presenter is not null!");
        }
        return presenter;
    }

    @Override
    public void setPresenter(P presenter) {
        mvpCallback.setPresenter(presenter);
    }

    @Override
    public V getView() {
        return mvpCallback.getView();
    }

    public void attachView(){
        getPresenter().attachView(getView());
    }

    public void detachView(){
        getPresenter().detachView();
    }

}
